#!/bin/bash
# 执行示例：sh buildAndK8sDeploy.sh test v6 platform-manager-api 或 sh buildAndK8sDeploy.sh test  或 sh buildAndK8sDeploy.sh test v6
#特别注意：如果在window上编辑完，上传到服务器执行，一定记得执行set ff=unix,否则会因为编码格式导致各种执行问题
#需要提前设置好环境变量HARBOR_URL，然后在本机执行docker login
tag=$(date +%Y%m%d_%H%M%S)
projectName=platform-manager-api
profile='test'
if [ $# -eq 0 ];
then
  echo "Params is need! example: sh buildAndK8sDeploy.sh test v6 platform-manager-api  or sh buildAndK8sDeploy.sh test v6 or sh sh buildAndK8sDeploy.sh test"
  exit
fi

if [ $# -eq 1 ];
then
  profile=$1
fi

if [ $# -eq 2 ];
then
  profile=$1
  tag=$2
fi

if [ $# -eq 3 ];
then
  profile=$1
  tag=$2
  projectName=$3
fi

# 注意[] 字符和判断条件 之间一定要有间隔
if  [ -z $HARBOR_URL ]; then
    echo "HARBOR_URL is need for environment variable,example: export HARBOR_URL=192.168.0.12:8081/weng"
    exit
fi

# 注意[] 字符和判断条件 之间一定要有间隔
if  [ -z $KUBOARD_URL ]; then
    echo "KUBOARD_URL is need for environment variable, It is use for CI,example: export KUBOARD_URL=192.168.0.12:10080"
    exit
fi

# 注意[] 字符和判断条件 之间一定要有间隔
if  [ -z $KuboardAccessKey ]; then
    echo "KuboardAccessKey is need for environment variable, It is use for CI,example: export KuboardAccessKey=e5ypxtwawcc3.b43n8bycb7cpn26mx7djbzah7nzd87tz"
    exit
fi

# 注意[] 字符和判断条件 之间一定要有间隔
echo "start to build project:$projectName profile:$profile tag:$tag "
isbuildSuccess= mvn clean assembly:assembly -P$profile
echo $isbuildSuccess
imageName=$HARBOR_URL/$projectName
imageNameTag=$imageName:$tag
docker build -t $imageNameTag ./
docker push $imageNameTag
docker rmi -f $imageNameTag
echo "build success and pushed images to harbor finish! project:$projectName profile:$profile"

echo "start deploy to k8s :$projectName tag:$tag "
curl -X PUT \
    -H "content-type: application/json" \
    -H "Cookie: KuboardUsername=admin; KuboardAccessKey=$KuboardAccessKey" \
    -d '{"kind":"deployments","namespace":"default","name":"'$projectName'","images":{"'$imageName'":"'$imageNameTag'"}}' \
    "http://"$KUBOARD_URL"/kuboard-api/cluster/test/kind/CICDApi/admin/resource/updateImageTag"

echo "deploy to k8s success ! project:$projectName image:$imageNameTag kuboardUrl:$KUBOARD_URL"